/**
 * 公共请求文件
 */

import axios from 'axios';
import { message } from 'antd';
import teacherStore from 'store/teacher';

const serve = axios.create({
    timeout: process.env.REACT_APP_TIMEOUT,
    baseURL: process.env.REACT_APP_BASE_URL
});

serve.interceptors.request.use(config => {
    teacherStore.token && (config.headers.Authorization = 'bearer ' + teacherStore.token);
    return config;
}, error => Promise.reject(error));

serve.interceptors.response.use(response => {
    const { code, msg, data, total } = response.data;
    const { newtoken } = response.headers;
    newtoken && teacherStore.setToken(newtoken);
    if (code === 0) {
        message.error(msg);
        return Promise.reject(code);
    }
    msg && message.success(msg);
    return undefined === total ? data : { total, data };
}, error => {
    const msg = (error + '').toLowerCase();
    if (msg.includes('timeout')) {
        message.error('请求超时，请检查网络是否畅通');
        return Promise.reject(error);
    }
    if (msg.includes('network error')) {
        message.error('请求失败，请检查您的网络是否正常');
        return Promise.reject(error);
    }
    const { status } = error.response;
    switch (status) {
        case 401:
            message.error('身份校验失败，请重新登录');
            teacherStore.exit();
            break;
        case 404:
            message.error('您请求的接口不存在');
            break;
        case 500:
            message.error('服务器内部错误');
            break;
        case 400:
            message.error('请求失败，请检查您的传参是否正确');
            break;
    }
    return Promise.reject(error);
});

export default serve;